package com.wang.controller;

import com.alibaba.fastjson.JSON;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.wang.auto.addSet.AddSetAutoSend;
import com.wang.auto.addSet.AddSetControlUtil;
import com.wang.conf.AppData;
import com.wang.packpojo.ConMsg;
import com.wang.packpojo.MsgStatus;
import com.wang.packpojo.ResultStatus;
import com.wang.pojo.*;
import com.wang.service.CalibrationReturnService;
import com.wang.service.CalibrationReturnServiceImpl;
import com.wang.socket.OutBoundHandler;
import com.wang.socket.SocketMap;
import com.wang.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


//校准配置 通讯服务
@RestController
public class CalibrationConfController  extends BaseController{


    private static Logger logger = LoggerFactory.getLogger(CalibrationConfController.class);

   //执行校准配置 通讯服务
    @RequestMapping(value = "/exeCalibration")
    @CrossOrigin
    public ResultStatus exeCalibration(Integer controlId, String calibrationValue) throws InterruptedException {



        ResultStatus msg = new ResultStatus();
        //判断该设备是否在线
        CalibrationControl calibrationControl = calibrationControlService.getById(controlId);
        Device device = deviceService.selectDeviceByDevId(calibrationControl.getDevId());
        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(device.getDevGId())) {
                conMsg = entry.getValue();
                break;
            }
        }

        if (conMsg != null) {

            //计算发送数据
            StringBuilder sb = new StringBuilder();
            //添加485地址
            sb.append(calibrationControl.getAddressCode());
            //添加功能码
            sb.append(calibrationControl.getFunCode());
            //添加起始地址
            sb.append(calibrationControl.getStartHex());
            if(calibrationControl.getDataType().equals("FLOAT")){
                //添加寄存器数量
                sb.append("0002");
                //添加字节数
                sb.append("04");
            }
            //填写数据
           Float f = Float.valueOf(calibrationValue);
           String hexValue = Integer.toHexString(Float.floatToIntBits(f));

           //添加实际数据
           sb.append(hexValue);
            //添加CRC校验
            //计算CRC
            byte[] checkBytes = ModBusUtil.HexString2Bytes(sb.toString());
            String CrcValue = ModBusUtil.getCRC3(checkBytes);
            sb.append(CrcValue);

            //去除所有的空格
            byte[] commandByte = ModBusUtil.HexString2Bytes(sb.toString());
            //对象锁
            Object object = new Object();
            ConMsg finalConMsg = conMsg;
            new Thread(() -> {
                synchronized (object) {
                    //发送给设备
                    OutBoundHandler.outData(finalConMsg.getCtx(), commandByte);

                    //创建全局变量对象
                    Map<String, Object> resultMap1 = new HashMap<>();
                    resultMap1.put(calibrationControl.getControlId().toString(), null);
                    AppData.returnMap.put(device.getDevGId(),resultMap1);

                    PrintUtil.print("服务端发送指令-->设备编码：" + device.getDevGId() + "：" + sb.toString());
                    //计数器  //小于10秒
                    int i = 0;
                    while (i < 100) {
                        Map<String, Object> resultMap = AppData.returnMap.get(device.getDevGId());
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(controlId.toString()) && resultMap.get(controlId.toString()) != null) {

                            System.out.println("开始激活");
                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();

            synchronized (object) {
                System.out.println("开始等待");
                object.wait(30000L);
            }
            Map<String, Object> resultMap = AppData.returnMap.get(device.getDevGId());



            if (resultMap != null && resultMap.containsKey(controlId.toString()) && resultMap.get(controlId.toString())!=null) {

                String returnData = resultMap.get(controlId.toString()).toString();
                PrintUtil.print("指令" + sb.toString() + "http://返回结果:" + returnData);
                //判断返回值比对
                CalibrationReturnService calibrationReturnService = SpringUtil.getBean("calibrationReturnServiceImpl", CalibrationReturnServiceImpl.class);
                CalibrationReturn  calibrationReturn = calibrationReturnService.selectByControlId(controlId);
                if(calibrationReturn.getControlReturnData().replaceAll(" ","").equals(returnData.replaceAll(" ",""))){
                    msg = new ResultStatus("success", "操作成功");
                }else {
                    msg = new ResultStatus("error", "设备响应失败，数据错误");
                }
            } else {
                msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
            }
            AppData.returnMap.remove(device.getDevGId());

        }else {
            msg = new ResultStatus("error", "设备离线，无法设置");
        }

        return msg;
    }
}
